import React, { useEffect } from "react";
import {
  View,
  Text,
  StyleSheet,
  ActivityIndicator,
  RefreshControl,
  Image,
  FlatList,
} from "react-native";
import { observer } from "mobx-react-lite";
import messageStore from "../../store/messageStore";

const MessagesScreen: React.FC = observer(() => {
  const {
    users,
    isRefreshing,
    isLoading,
    hasMore,
    onRefresh,
    onLoadMore,
    loadData,
  } = messageStore;

  useEffect(() => {
    loadData();
  }, []);
  const renderFooter = () => (
    <>
      {isLoading && <ActivityIndicator size="large" color="#0000ff" />}
      {!hasMore && !isLoading && (
        <Text style={styles.footerText}>没有更多数据了</Text>
      )}
    </>
  );

  const renderItem = (user: any) => {
    return (
      <View style={styles.contentView}>
        <Image
          source={{ uri: user.avatar }}
          style={styles.avatar}
          resizeMode="cover"
        />
        <View style={styles.userInfo}>
          <Text style={styles.name}>
            {user.first_name} {user.last_name}
          </Text>
          <Text style={styles.email}>{user.email}</Text>
        </View>
      </View>
    );
  };

  return (
    <FlatList
      data={users}
      renderItem={({ item }) => renderItem(item)}
      keyExtractor={(item) => item.id.toString()}
      refreshControl={
        <RefreshControl refreshing={isRefreshing} onRefresh={onRefresh} />
      }
      onEndReached={onLoadMore}
      ListFooterComponent={renderFooter}
    />
  );
});

const styles = StyleSheet.create({
  contentView: {
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: "#f9f9f9",
    marginVertical: 5,
    marginHorizontal: 10,
    padding: 10,
    borderRadius: 8,
    elevation: 2,
    height: 150,
  },
  avatar: {
    width: 50,
    height: 50,
    borderRadius: 25,
  },
  userInfo: {
    flex: 1,
    marginLeft: 10,
  },
  name: {
    fontWeight: "bold",
    fontSize: 16,
    color: "#333",
  },
  email: {
    fontSize: 14,
    color: "#555",
    marginTop: 4,
  },
  footerText: {
    paddingVertical: 20,
    textAlign: "center",
    fontSize: 14,
    color: "#888",
  },
});

export default MessagesScreen;
